import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class problem2 {
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};

    public int rotApple(ArrayList<ArrayList<Integer>> grid) {
        int m = grid.size();
        int n = grid.get(0).size();
        boolean[][] vis = new boolean[m][n];

        Queue<int[]> queue = new LinkedList<>();

        //找到原本坏掉的苹果
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid.get(i).get(j) == 2) {
                    queue.add(new int[]{i, j});//存下标
                }
            }
        }

        //开始传染
        int ret = 0;
        while (!queue.isEmpty()) {
            int sz = queue.size();
            while (sz-- != 0) {
                int[] arr = queue.poll();
                int a = arr[0];
                int b = arr[1];
                for (int i = 0; i < 4; i++) {
                    int x = a + dx[i];
                    int y = b + dy[i];
                    if (x >= 0 && x < m && y >= 0 && y < n && grid.get(x).get(y) == 1 && vis[x][y] == false) {
                        vis[x][y] = false;
                        queue.add(new int[]{x, y});
                    }
                }
            }
            ret++;
        }

        //检查是否有没被传染的
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                //原来是好的 且没有被传染
                if (grid.get(i).get(j) == 1 && !vis[i][j]) {
                    return -1;
                }
            }
        }
        return ret - 1;
    }
}
